package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.UserInfo;
import com.scuec.groupfive.entity.SysLog;
import com.scuec.groupfive.mapper.SysLogMapper;
import com.scuec.groupfive.service.UserLoginService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/userlogin")
@CrossOrigin(maxAge = 3600)
public class UserLoginController {

    @Resource
    private UserLoginService userLoginService;

    @Resource
    private SysLogMapper sysLogMapper;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserInfo loginForm, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        UserInfo user = userLoginService.login(loginForm.getUsername(), loginForm.getPassword());

        if (user != null) {
            // 记录登录日志
            recordLoginLog(user, request);

            // 返回用户数据
            Map<String, Object> userData = new HashMap<>();
            userData.put("userId", user.getUserId());
            userData.put("username", user.getUsername());
            userData.put("role", user.getRole());
            userData.put("status", user.getStatus());
            userData.put("school", user.getSchool());
            userData.put("targetSchool", user.getTargetSchool());

            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("data", userData);
        } else {
            result.put("code", 401);
            result.put("msg", "账号或密码错误");
        }
        return result;
    }

    private void recordLoginLog(UserInfo user, HttpServletRequest request) {
        SysLog log = new SysLog();
        log.setUserID(user.getUserId());
        log.setLogContent("用户登录");
        log.setCreateDate(new Date());

        // 获取IP地址
        String ip = getClientIP(request);
        log.setIpAddress(ip);

        // 解析User-Agent
        String userAgentStr = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
        log.setOs(userAgent.getOperatingSystem().getName());
        log.setIe(userAgent.getBrowser().getName());

        sysLogMapper.insertLog(log);
    }

    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}